<?php

class Weather extends CActiveRecord
{
	public $cityAlias;
	public $cityTitle;
	
	public function tableName()
	{
		return lfirst(__CLASS__);
	}
	
	public static function model($className = __CLASS__)
    {
    	return parent::model(lfirst(__CLASS__));
    }
    
    public static function getWeatherConfig()
    {
    	$config = new CConfiguration('protected/config/weather.php');
		$config = $config->toArray();
		
		return $config['weather'];
    }
    
    public function checkAccess($key)
    {
    	$config = $this->getWeatherConfig();
    	
    	if ($config['key'] == $key) {
    		return true;
    	}
    	
    	return false;
    }
    
    public function updateData()
    {
		set_time_limit(0);
    	
    	$config = $this->getWeatherConfig();
		
		if (array_key_exists('vendor', $config)) {
			
			$cities = City::model()->findAll();
			
			$className  = $config['vendor'] . 'Weather';
			$weatherObj = new $className;
			
			foreach ($cities as $city) {
				$cityAlias = strval($city->alias);
				
				if ($cityAlias != '') {
					$data = $weatherObj->setPlace($cityAlias)
						   				 	 ->parseXml()
						   				 	 ->getSimpleInformation();
						   				 	 
					if ($data) {
						self::model()->updateAll($data, 'cityId=:cityId', array(':cityId' => $city->id));
					}
				}
				
				sleep(2);
			}
		} else {
			throw new Exception('Undefined vandor value in weather config file');
		}
    }
    
	public function findWeatherInCities($weatherOnSite = true)
	{
		$criteria = new CDbCriteria();
		$criteria->select = array('weather.*', 'city.alias as cityAlias', 'city.title as cityTitle');
		$criteria->join = 'inner join city ON city.id=cityId';
		
		if ($weatherOnSite) {
			$criteria->condition = "city.weatherOnSite = 1";
		} else {
			$criteria->condition = "city.alias <> '' and city.alias is not null and weather.temperature is not null";
		}
		
		$criteria->order = "city.title asc";
		
			
		return self::model()->findAll($criteria);
	}
}